package org.example.myleet.p443;

/**
 * 读指针、写指针、原地修改
 */
public class Solution {
    public int compress(char[] chars) {
        if (chars.length == 1) {
            return 1;
        }
        int writeIdx = 0;
        char c0 = chars[0];
        int count = 1;
        char c1;
        int readIdx = 1;
        while (readIdx < chars.length) {
            c1 = chars[readIdx++];
            if (c1 == c0) {
                ++count;
            } else {
                chars[writeIdx++] = c0;
                if (count > 1) {
                    //大于1的情况下将数字拆分成字符数组写入数组中
                    String countStr = count + "";
                    for (char num : countStr.toCharArray()) {
                        chars[writeIdx++] = num;
                    }
                }
                count = 1;
            }
            c0 = c1;
        }
        chars[writeIdx++] = c0;
        if (count > 1) {
            String countStr = count + "";
            for (char num : countStr.toCharArray()) {
                chars[writeIdx++] = num;
            }
        }
        return writeIdx;
    }
}
